package com.rn.gypsophila.dsalg.string;

/**
 * 题目：给你一个字符串 s，找到 s 中最长的回文子串。如果字符串的反序与原始字符串相同，则该字符串称为回文字符串。
 * 链接：<a href="https://leetcode.cn/leetbook/read/array-and-string/conm7/">...</a>
 *
 * @author 然诺
 * @since 2023/3/19
 */
public class LongestPalindrome {

    /**
     * 暴力循环法
     * 时间复杂度：O(N^3)
     * 空间复杂度：O(1)
     */
    public static String longestPalindromeV1(String s) {
        if (s == null) {
            return null;
        }
        int len = s.length();
        if (len <= 1) {
            return s;
        }
        int maxLen = 0;
        int beginIdx = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < len - 1; i++) {
            for (int j = i + maxLen; j < len; j++) {
                int newMaxLen = j - i + 1;
                if (isPalindrome(chars, i, j) && newMaxLen > maxLen) {
                    maxLen = newMaxLen;
                    beginIdx = i;
                }
            }
        }
        return s.substring(beginIdx, beginIdx + maxLen);
    }

    private static boolean isPalindrome(char[] chars, int left, int right) {
        while (left <= right) {
            if (chars[left] != chars[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    /**
     * 动态规划法
     * 时间复杂度：O(N^2)
     * 空间复杂度：O(N^2)
     */
    public static String longestPalindromeV2(String s) {
        if (s == null) {
            return null;
        }
        int len = s.length();
        if (len <= 1) {
            return s;
        }
        int maxLen = 1;
        int beginIdx = 0;
        boolean[][] dp = new boolean[len][len];
        char[] chars = s.toCharArray();
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }
        for (int j = 1; j < len; j++) {
            for (int i = 0; i < j; i++) {
                if (chars[i] != chars[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 2) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                    beginIdx = i;
                }
            }
        }
        return s.substring(beginIdx, beginIdx + maxLen);
    }

    public static void main(String[] args) {
        String s = "babad";
        System.out.println(longestPalindromeV1(s));
    }

}
